import 'package:dio_demo/ArticleDetailPage.dart';
import 'package:dio_demo/widget/EmptyImgWidget.dart';
import 'package:dio_demo/widget/FirstRefreshWidget.dart';
import 'package:flutter/material.dart';
import 'api/ArticleApi.dart';
import 'bean/article_list_resp_entity.dart';
import 'net/ApiException.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class ListPage extends StatefulWidget {
  const ListPage({super.key, required this.title});

  final String title;

  @override
  State<ListPage> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage> {
  // 列表数据
  final List<Article> _articles = [];

  // 当前页码
  int _page = 1;

  // 每页数量
  final int _pageSize = 10;

  // 是否还有更多数据
  bool _hasMore = true;

  // EasyRefresh控制器
  final EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    EasyRefresh.defaultHeader = MaterialHeader(backgroundColor: Colors.white);
    EasyRefresh.defaultFooter = BallPulseFooter(color: Colors.blue);
    //
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          centerTitle: true, // 标题居中显示
        ),
        body: EasyRefresh(
          controller: _controller,
          onRefresh: () async {
            await _getArticleList(true);
          },
          onLoad: _hasMore
              ? () async {
                  await _getArticleList(false);
                }
              : null,
          firstRefresh: true,
          firstRefreshWidget: const FirstRefreshWidget(),
          emptyWidget: _articles.isEmpty
              ? EmptyImgWidget(
                  title: '暂无数据,点击刷新',
                  onTap: () {
                    _getArticleList(true);
                  },
                )
              : null,
          child: ListView.builder(
              itemCount: _articles.length,
              itemBuilder: (context, index) {
                final article = _articles[index];
                return InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => ArticleDetailPage(
                            title: article.title,
                            url: article.link,
                          ),
                        ),
                      );
                    },
                    child: _buildArticleItem(
                      article,
                    ));
              }),
        ));
  }

  // 在你的某个 Widget 的 State 中
  Future<void> _getArticleList(bool isRefresh) async {
    try {
      setState(() {
        // 显示 loading
      });
      if (isRefresh) {
        _page = 1;
      } else {
        _page++;
      }
      final articleList = await ArticleApi.getArticleList(_page, _pageSize);
      setState(() {
        if (isRefresh) {
          _articles.clear();
        }
        _articles.addAll(articleList);
        print("获取成功：articleList.length = ${articleList.length}");
        _hasMore = articleList.isNotEmpty;
      });
      if (isRefresh) {
        _controller.finishRefresh(success: true);
      } else {
        _controller.finishLoad(success: true, noMore: !_hasMore);
      }
    } on ApiException catch (e) {
      if (isRefresh) {
        _controller.finishRefresh(success: true);
      } else {
        _controller.finishLoad(success: true, noMore: !_hasMore);
      }
      // 捕获我们自定义的异常，进行统一的 UI 提示
      print('获取失败: code=${e.code}, message=${e.message}');
      // 弹出一个 Toast 或 Dialog
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text(e.message)));
    } finally {
      setState(() {
        // 隐藏 loading
      });
    }
  }

  // 文章列表项
  Widget _buildArticleItem(Article article) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              article.title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 8),
            Text(
              article.desc,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.black54,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  article.author.isNotEmpty
                      ? article.author
                      : article.shareUser,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
                Text(
                  article.niceDate,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
